FUZZER_NAME := 'libfuzzer_stb_image_sugar'
PROJECT_DIR := absolute_path(".")
CARGO_TARGET_DIR := env("CARGO_TARGET_DIR", "target")
PROFILE := env("PROFILE", "release")
PROFILE_DIR := if PROFILE == "release" { "release" } else if PROFILE == "dev" { "debug" } else { "debug" }

EXTENSION := if os() == "windows" {".exe"} else { "" }
LIBAFL_CC := PROJECT_DIR / CARGO_TARGET_DIR / PROFILE_DIR / "libafl_cc" + EXTENSION
LIBAFL_CXX := PROJECT_DIR / CARGO_TARGET_DIR / PROFILE_DIR / "libafl_cxx" + EXTENSION
 
FUZZER := PROJECT_DIR / CARGO_TARGET_DIR / PROFILE_DIR / FUZZER_NAME + EXTENSION

alias cc := cxx

cxx:
    cargo build --profile {{PROFILE}}

fuzzer: cxx
    #!/bin/bash
    cargo build --profile {{PROFILE}}
    {{LIBAFL_CC}} -o ./{{FUZZER_NAME}} harness.c -lglib-2.0 -lgio-2.0 -lgmodule-2.0

[linux]
[macos]
run: fuzzer
    #!/bin/bash
    ./{{FUZZER_NAME}} &
    sleep 0.2

[windows]
run: fuzzer
    echo "Not integrated into just yet."

[linux]
[macos]
test: fuzzer
    #!/bin/bash
    success=0
    rm -rf libafl_unix_shmem_server || true
    timeout 5s ./{{FUZZER_NAME}} >fuzz_stdout.log
    while read -r line; do
        corpus_number=$(echo "$line" | cut -d' ' -f2)
        if (( corpus_number > 50 )); then
            success=1
        fi
    done < <(grep -o 'corpus: [0-9]\+' fuzz_stdout.log)

    if [ "$success" -eq 1 ]; then
        echo "Fuzzer is working!"
        exit 0
    else
        echo "Fuzzer not working!"
        exit 1
    fi
    
clean:
    #!/bin/bash
    rm -f {{FUZZER_NAME}}
    cargo clean
